<?php

namespace App\Models;

use DB;

class MemberCash extends BaseModel
{
    protected $table = "member_cash";

    protected $rules = [
        'admin_id' => 'required',
        'shop_id' => 'required',
        'mid' => 'required',
        'lose_pay' => 'numeric',
        'self_bucket' => 'required|numeric',
        'cash_bucket' => 'required|numeric',
        'cash' => 'required|numeric',
        'water_dispenser' => 'required|numeric',
        'water_dispenser_cash' => 'required|numeric',
    ];

    protected $message = [
        'admin_id.required' => '商户信息失败',
        'shop_id.required' => '店铺信息获取失败',
        'mid.required' => '用户信息获取失败',
        'lose_pay.numeric' => '水桶丢损赔付金额必须是纯数字',
        'self_bucket.required' => '自备桶数量必须填写',
        'self_bucket.numeric' => '自备桶数量必须是纯数字',
        'cash_bucket.required' => '押金桶数量必须填写',
        'cash_bucket.numeric' => '押金桶数量必须是纯数字',
        'cash.required' => '水桶押金必须填写',
        'cash.numeric' => '水桶押金必须是纯数字',
        'water_dispenser.required' => '饮水机数量必须填写',
        'water_dispenser.numeric' => '饮水机数量必须是纯数字',
        'water_dispenser_cash.required' => '饮水机押金必须填写',
        'water_dispenser_cash.numeric' => '饮水机押金必须是纯数字',

        'order_amount.regex' => '商品价格不能小于0',
    ];

    public function member()
    {
        return $this->hasOne('App\Models\Member', 'mid', 'id');
    }

    public function address()
    {
        return $this->hasOne('App\Models\Address', 'mid', 'mid');
    }

    public function getInfoById()
    {
        $info = $this->_getJionOne('member', ['mid' => request('id')]);
        return $info;
    }

    public function getList()
    {
        $keyword = trim(request('keyword', ''));
        $type = request('type');
        $start = request('time-start');
        $end = request('time-end');
        $status = request('status', 'all');
        $where['shop_id'] = session('shop_info.id');
        is_numeric($status) && $where['status'] = $status;
        $condition = [];
        switch ($type) {
            case 1:
                $where['mid'] = $keyword;
                break;
            case 2:
                $condition = ['name' => ['like', "%$keyword%"]];
                break;
            case 3:
                $condition = ['mobile' => ['like', "%$keyword%"]];
                break;
            case 4:
                $condition = ['company_name' => ['like', "%$keyword%"]];
                break;
            case 5:
                $condition = ['address' => ['like', "%$keyword%"]];
                break;
        }
        if (count($condition)) {
            $address = new Address();
            $res = $address->_getList($condition, 'mid');
            if (!$res) {
                $rows['data'] = [];
                return $rows;
            }
            $ids = [];
            foreach ($res as $v) {
                $ids[] = $v['mid'];
            }
            $where['mid'] = ['in', $ids];
        }
        if ($start && !$end) {
            $where['addtime'] = ['>=', strtotime($start)];
        }
        if ($end && !$start) {
            $where['addtime'] = ['<=', strtotime($end)];
        }
        if ($start && $end) {
            $timeArea = [strtotime($start), strtotime($end)];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        $rows = $this->_getJoinPageList('address', $where, '*', ['id' => 'desc'], 15, 5, 'id,mid,name,mobile,company_name,address', ['is_default' => 1]);
        $txtStr['status'] = [0 => '未退', 1 => '已退'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }


    public function getOrderListWithGoods()
    {
        $keyword = request('keyword');
        $where['admin_id'] = request('aid');
        $where['shop_id'] = request('sid');
        $where['buyer_id'] = request('mid');
        if ($keyword) {
            $where['order_sn'] = ['like', '%' . $keyword . '%'];
        }
        return $this->_getJoinPageList('orderGoods', $where, '*', ['sort' => 'asc'], 10, 5, 'id,goods_id,goods_name,goods_price,goods_num', ['shop_id' => $where['shop_id']]);
    }


    public function addOrUpdate($shopId)
    {
        $data['mid'] = request('mid');
        if (request('id')) {
            $data['id'] = request('id');
            $record = $this->_getOneById(request('id'));
            if ($record['status']) {
                $this->error = '非法操作！';
                return false;
            }
            $data['status'] = 1;
            $data['back_cash_bucket_num'] = intval(request('back_cash_bucket_num', 0));
            $data['back_cash_bucket_category'] = intval(request('back_cash_bucket_category', 0));
            $data['back_self_bucket_num'] = intval(request('back_self_bucket_num', 0));
            $data['back_self_bucket_category'] = request('back_self_bucket_category', 0);
            $data['back_bucket_money'] = doubleval(request('back_bucket_money', 0));
            $data['back_water_dispenser_num'] = intval(request('back_water_dispenser_num', 0));
            $data['back_water_dispenser_money'] = doubleval(request('back_water_dispenser_money', 0));
            $data['back_description'] = trim(request('back_description'));
        } else {
//            $where['mid'] = request('mid');
//            $where['status'] = 0;
//            $record = $this->_getOne($where);
//            if ($record) {
//                $this->error = '该用户还有未退押金，请勿重复添加！';
//                return false;
//            }
            $data['addtime'] = time();
            $data['shop_id'] = $shopId;
            $data['admin_id'] = plat_admin_id();
            $data['lose_pay'] = doubleval(request('lose_pay', 0));
            $data['self_bucket'] = intval(request('self_bucket', 0));
            request('self_bucket_category') && $data['self_bucket_category'] = request('self_bucket_category');
            $data['cash_bucket'] = intval(request('cash_bucket', 0));
            $data['cash_bucket_category'] = request('cash_bucket_category');
            $data['cash'] = doubleval(request('cash', 0));
            $data['water_dispenser'] = intval(request('water_dispenser', 0));
            $data['water_dispenser_cash'] = doubleval(request('water_dispenser_cash', 0));
            $data['description'] = trim(request('description'));
            if (!$this->_validate($data)) {
                return false;
            }
        }
        $this->_start();
        $res = $this->_save($data);
        if (!$res) {
            $this->_rollBack();
            $this->error = '保存押金信息失败！';
            return false;
        }
        $member = new Member();
        $memberInfo = $member->_getOneById($data['mid']);
        $memberData['id'] = $data['mid'];
        //退还押金
        if (isset($data['id'])) {
            $cashInfo = $this->_getOne(['mid' => $data['mid'], 'status' => 0, 'id' => ['<>', $data['id']]], 'id');
            $deposit = $data['back_bucket_money'];
            //当前押金为最后一张押金条时，表示该用户与水站之间清算完毕，用户押金、水桶和水票信息将全部清零
            if (!$cashInfo) {
                $memberData['initial_bucket_num'] = 0;
                $memberData['self_bucket_num'] = 0;
                $memberData['cash_bucket_num'] = 0;
                $memberData['deposit'] = 0;
                $memberData['borrow_bucket_num'] = 0;
                $memberData['total_bucket_num'] = 0;
                $memberData['total_back_bucket_num'] = 0;
                $memberData['total_waterbill_num'] = 0;
                $memberData['initial_bucket_category'] = 0;
                $memberData['self_bucket_category'] = 0;
                $res = $member->_save($memberData);
                $memberWaterBill = new MemberWaterBill();
                //水票清零
                $memberWaterBill->_update(['mid' => $data['mid']], ['rest_num' => 0]);
                //清除用户水票缓存
                $memberWaterBill->_redisGenerateBillListByMid($data['mid']);
            } else {
                $borrow_bucket_num = $memberInfo['initial_bucket_num'] + $memberInfo['total_bucket_num'] - $memberInfo['total_back_bucket_num'] - ($memberInfo['cash_bucket_num'] - $data['back_cash_bucket_num']) - ($memberInfo['self_bucket_num'] - $data['back_self_bucket_num']);
                $memberData = [
                    'self_bucket_num' => "`self_bucket_num` - {$data['back_self_bucket_num']}",
                    'cash_bucket_num' => "`cash_bucket_num` - {$data['back_cash_bucket_num']}",
                    'deposit' => "`deposit` - {$data['back_bucket_money']}",
                    'borrow_bucket_num' => $borrow_bucket_num
                ];
                $res = $member->_updateOrigin(['id' => $data['mid']], $memberData);
            }
        } else {
//            $memberData['self_bucket_num'] = $data['self_bucket'];
//            $memberData['cash_bucket_num'] = $data['cash_bucket'];
//            $memberData['deposit'] = $data['cash'] + $data['water_dispenser_cash'];
//            $memberData['borrow_bucket_num'] = $memberInfo['initial_bucket_num'] + $memberInfo['total_bucket_num'] - $memberInfo['total_back_bucket_num'] - $data['cash_bucket'];
            $deposit = $data['cash'] + $data['water_dispenser_cash'];
            $borrow_bucket_num = $memberInfo['initial_bucket_num'] + $memberInfo['total_bucket_num'] - $memberInfo['total_back_bucket_num'] - $memberInfo['cash_bucket_num'] - $data['cash_bucket'] - $data['self_bucket'];
            $memberData = [
                'self_bucket_num' => "`self_bucket_num` + {$data['self_bucket']}",
                'cash_bucket_num' => "`cash_bucket_num` + {$data['cash_bucket']}",
                'deposit' => "`deposit` + {$deposit}",
                'borrow_bucket_num' => $borrow_bucket_num,
            ];
//            dd($memberData);
            $res = $member->_updateOrigin(['id' => $data['mid']], $memberData);
        }
//        $res = $member->_save($memberData);
        if (!$res) {
            $this->_rollBack();
            $this->error = '更新用户信息失败！';
            return false;
        }
        $shop = new Shop();
        //更新店铺押金
        if (!isset($data['id'])) {
            $shop->_inc(['id' => $shopId], 'deposit', $deposit);
        } else {
            $shop->_dec(['id' => $shopId], 'deposit', $deposit);
        }
        $this->_commit();
        return $data;
    }

}
